package com.zjuh.qss.biz.bo.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import wint.lang.utils.CollectionUtil;
import wint.lang.utils.MapUtil;
import wint.lang.utils.StringUtil;

import com.taobao.api.domain.TradeRate;
import com.zjuh.qss.biz.bo.PagedResult;
import com.zjuh.qss.biz.bo.TradeRateBO;
import com.zjuh.qss.common.http.ClientConnector;
import com.zjuh.qss.common.http.ClientResponse;
import com.zjuh.qss.common.http.JDKClientConnector;

public class TradeRateBOImpl implements TradeRateBO {

	private ClientConnector clientConnector = new JDKClientConnector();
	
	public PagedResult<TradeRate> searchTraderates(long userId, long auctionId, int page) {
		String url = "http://rate.taobao.com/feedRateList.htm?userNumId="+userId
		+"&auctionNumId="+auctionId
		+"&currentPageNum="+page
		+"&rateType=&orderType=sort_weight&showContent=1&attribute=&callback=jsonp_reviews_list";
		String content = doGetForString(url);
		PagedResult<TradeRate> pagedResult = new PagedResult<TradeRate>();
		try {
			content = content.trim();
			content = StringUtil.getFirstAfter(content, "jsonp_reviews_list(");
			content = StringUtil.getLastBefore(content, ")");
			
			JSONObject json = new JSONObject(content);
			
			int maxPage = json.getInt("maxPage");
			pagedResult.setMaxPage(maxPage);
			List<TradeRate> rates = CollectionUtil.newArrayList();
			
			if (!json.has("comments")) {
				pagedResult.setResults(rates);
				return pagedResult;
			}
			
			
			JSONArray array = json.getJSONArray("comments");
			
			for (int i = 0, len = array.length(); i < len ; ++i) {
				JSONObject rateJson = array.getJSONObject(i);
				TradeRate tradeRate = new TradeRate();
				String rateContent = rateJson.getString("content");
				int rate = rateJson.getInt("rate");
				if (rate != 1) {
					continue;
				}
				tradeRate.setContent(rateContent);
				rates.add(tradeRate);
			}
			pagedResult.setResults(rates);
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}
		return pagedResult;
	}
	
	private String doGetForString(String url) {
		try {
			ClientResponse clientResponse = clientConnector.request(url, false, null, null, null, null);
			byte[] data = clientResponse.getData();
			String charset = getCharset(clientResponse.getHeaders());
			if (StringUtil.isEmpty(charset)) {
				charset = "utf-8";
			}
			return new String(data, charset);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	private String getCharset(Map<String, List<String>> rawHeaders) {
		Map<String, List<String>> lowerCaseHeaders = MapUtil.newHashMap();
		for (Map.Entry<String, List<String>> entry : rawHeaders.entrySet()) {
			String name = entry.getKey();
			if (StringUtil.isEmpty(name)) {
				continue;
			}
			List<String> value = entry.getValue();
			lowerCaseHeaders.put(name.toLowerCase(), value);
		}
		List<String> contentTypes = lowerCaseHeaders.get("content-type");
		if (CollectionUtil.isEmpty(contentTypes)) {
			return null;
		}
		String contentType = contentTypes.get(0);
		String[] parts = contentType.split(";");
		for (String part : parts) {
			if (StringUtil.isEmpty(part)) {
				continue;
			}
			String lowercasePart = part.toLowerCase();
			if (lowercasePart.contains("charset") && lowercasePart.contains("=")) {
				String ret = StringUtil.getFirstAfter(lowercasePart, "=");
				ret = StringUtil.trimToEmpty(ret);
				return ret;
			}
		}
		return null;
	}
	
}
